package com.itaem.crazy.shirodemo.modules.shiro.controller;


import com.alibaba.fastjson.JSONObject;
import com.itaem.crazy.shirodemo.modules.shiro.entity.User;
import com.itaem.crazy.shirodemo.modules.shiro.service.ShiroService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import javax.xml.transform.Result;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * 测试shiro接口
 * 用户登入登出
 */
@RestController
public class ShiroController {

    @Autowired
    private ShiroService shiroService;


    // 登录测试(前提是数据库以及写入测试数据)
    // http://localhost:9090/river/sys/login?username=Jack&password=123
    @ApiOperation(value = "登陆", notes = "参数:用户名 密码")
    @GetMapping("/sys/login")
    public Map<String, Object> login(String username, String password)  {
        Map<String, Object> result = new HashMap<>();
        //用户信息
        User user = shiroService.findByUsername(username);
        //账号不存在、密码错误
        if (user==null||!user.getPassword().equals(password)) {
            result.put("status", "400");
            result.put("msg", "账号或密码有误");
            return result;
        } else {
            /*Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);*/
            //生成token，并保存到数据库
            result = shiroService.createToken(user.getUserId());
            result.put("status", "200");
            result.put("msg", "登陆成功");
            return result;
        }
    }


    //注册
    @ApiOperation(value = "注册", notes = "参数:系统用户实体")
    @PostMapping(value = "/sys/signUp")
    public Object insertUser(@NotNull @RequestBody User user, HttpServletRequest request, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        //将uuid设置为密码盐值
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        SimpleHash simpleHash = new SimpleHash("MD5", user.getPassword(), salt, 1024);
        //添加用户信息
        user.setPassword(user.getPassword());
        user.setValid(1);  //默认1
        user.setSalt(salt);
        user.setCreateTime(new Date());
        user.setDel(0);
        Boolean bool = shiroService.insert(user);
        jsonObject.put("success", bool);
        jsonObject.put("msg", bool?"注册成功。":"注册失败！");
        return jsonObject;
    }


    // 退出
    @PostMapping("/sys/logout")
    public Map<String, Object> logout(String token) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        //System.out.println("用户id："+user.getUserId());
        if (user == null) {
            result.put("status", "201");
            result.put("msg", "系统未登录！");
        }else {
            shiroService.logout(user.getUserId());
            SecurityUtils.getSubject().logout();
            result.put("status", "200");
            result.put("msg", "注销成功。");
        }
        return result;
    }



}


